import React, { useState, useEffect } from 'react';
import '../antd.css';
import { Pick, NavPick } from 'pick/index';
import { Trace, NavTrace } from 'trace/index';
import { loc_set_en, loc_set_zh, obj_str, LayFrame, ListBox, CurModel, loc } from 'sui';
import { urlWork } from 'nui';

const g_model = () => {
    return [
        {id: "trace",   view: Trace,    nav: NavTrace,   desc: loc("serve_5")},
        {id: "pick",    view: Pick,     nav: NavPick,    desc: loc("serve_2")},
    ];
};

const ServerHome = () => {
    const [mod, setMod] = useState(CurModel.getItem("cur-model", "record"));
    const [event, setEvent] = useState("");

    useEffect(() => {
        urlWork(null, "config/file", {p: "user"},
            r => {
                const d = r[0];
                const lang = obj_str(d, "uiLanguage")
                if (lang === "zh") {
                    loc_set_zh();
                }
                else {
                    loc_set_en();
                }
            });
    }, []);

    const modChange = (v) => {
        if (v === mod) {
            return;
        }

        CurModel.setItem("cur-model", v);
        setMod(v);
    };

    const view = () => {
        const m = g_model();
        const md = mod.split(".");

        for (let i = 0; i < m.length; i++) {
            const d = m[i];
            if (d.id === md[0]) {
                const CurView = d.view;

                let tmp = md.splice(1);
                tmp = tmp.join(".");

                return <CurView mod={tmp} event={event} setEvent={setEvent} sideopen={true}/>;
            }
        }

        return null;
    };

    const item = () => {
        const m = g_model();

        return m.map(d => {
            const View = d.nav;
            return <View cur={mod} value={d.desc} uid={d.id} hcmd={modChange} key={d.id} event={event} setEvent={setEvent}/>;
        });
    };

    return (
        <LayFrame title="PLC" view={view} sideopen={true} size="dense">
            <ListBox>
                {item()}
            </ListBox>
        </LayFrame>
    );
};

export {ServerHome, g_model};
